//
//  PickerImagesViewDataProvider.swift
//  PickerImage
//
//  Created by ET|冰琳 on 2017/3/24.
//  Copyright © 2017年 IB. All rights reserved.
//

import Foundation
import ReactiveSwift


protocol PickerImageUploadService {
    //    associatedtype PickerImageUploadResult
    func upload(img: PickerImageCellModel, closure: @escaping (Progress) -> Void) -> SignalProducer<Any, NSError>
}

class PickerImagesViewDataProvider: NSObject {
    
    var images: [PickerImageCellModel] = []
    var maxImageCount: Int = 8
    let service: PickerImageUploadService
    
    init(service: PickerImageUploadService) {
        self.service = service
    }
    
    var autoUpload = true
    
    func numberOfRow() -> Int {
        
        let count = self.images.count
        if count >= maxImageCount {
            return maxImageCount
        }
        return count + 1
    }
    
    func addImages(images: [ImageInfoProperty]) {
        images.forEach { (e) in
            self.addImage(image: e)
        }
    }
    
    func addImage(image: ImageInfoProperty) {
        let model = PickerImageCellModel(entity: image)
        
        guard self.autoUpload else {
            self.images.append(model)
            return
        }
        
        service.upload(img: model, closure: { p in
            model.progress.value = CGFloat(p.completedUnitCount)/CGFloat(p.totalUnitCount)
        }).startWithResult { (result) in
            switch result {
            case .failure(_):
                model.isUploadSuceed.value = false
            case .success(_):
                model.isUploadSuceed.value = true
            }
        }
        
        self.images.append(model)
    }
    
    func removeImageAt(index: Int) {
        self.images.remove(at: index)
    }
    
    func changeImage(from: IndexPath, to: IndexPath) {
        let fromImg = self.images[from.row]
        self.images.replaceSubrange(from.row..<from.row+1, with: [self.images[to.row]])
        self.images.replaceSubrange(to.row..<to.row+1, with: [fromImg])
    }
}



